import React, { useState, useEffect } from 'react';
import { Space, Button, Input, List, Typography } from 'antd';

const { Text } = Typography;

export default function CanvasEditor({
  title,
  layerList = [],
  selectedLayer = null,
  onLayerUpdated,
  onLayerSelected,
  onCanvasSaved,
  onCanvasCleared,
}) {
  const [layers, setLayers] = useState(layerList || []);
  const [selected, setSelected] = useState(selectedLayer || null);
  const [newLayerName, setNewLayerName] = useState('');

  useEffect(() => {
    setLayers(layerList || []);
  }, [layerList]);

  useEffect(() => {
    setSelected(selectedLayer || null);
  }, [selectedLayer]);

  const addLayer = () => {
    const name = newLayerName.trim() || `Layer-${Date.now()}`;
    const updated = [...layers, { id: Date.now(), name }];
    setLayers(updated);
    setNewLayerName('');
    onLayerUpdated && onLayerUpdated(updated);
  };

  const removeLayer = (id) => {
    const updated = layers.filter(l => l.id !== id);
    setLayers(updated);
    if (selected?.id === id) setSelected(null);
    onLayerUpdated && onLayerUpdated(updated);
  };

  const selectLayer = (layer) => {
    setSelected(layer);
    onLayerSelected && onLayerSelected(layer);
  };

  const saveCanvas = () => {
    const canvasData = {
      layers: layers,
      canvasSize: { width: 270, height: 480 },
    };
    onCanvasSaved && onCanvasSaved(canvasData);
  };

  const clearCanvas = () => {
    setLayers([]);
    setSelected(null);
    onLayerUpdated && onLayerUpdated([]);
    onCanvasCleared && onCanvasCleared();
  };

  return (
    <Space direction="vertical" style={{ width: '100%' }}>
      <Text strong>{title}</Text>
      <Space>
        <Input
          placeholder="图层名称"
          value={newLayerName}
          onChange={(e) => setNewLayerName(e.target.value)}
          style={{ width: 240 }}
        />
        <Button type="primary" onClick={addLayer}>添加图层</Button>
        <Button onClick={saveCanvas}>保存画布</Button>
        <Button danger onClick={clearCanvas}>清空画布</Button>
      </Space>
      <List
        bordered
        dataSource={layers}
        renderItem={(item) => (
          <List.Item
            actions={[
              <Button size="small" onClick={() => selectLayer(item)}>选择</Button>,
              <Button size="small" danger onClick={() => removeLayer(item.id)}>删除</Button>,
            ]}
          >
            <Space>
              <Text>{item.name}</Text>
              {selected?.id === item.id && <Text type="success">(已选中)</Text>}
            </Space>
          </List.Item>
        )}
      />
    </Space>
  );
}